<script lang="ts">
  import { setContext } from 'svelte';
  import { writable } from 'svelte/store';
  import type { TabContext } from './conf';
  export let active = 0;
  export let prerender = false;
  const activeTab$ = writable(active);
  let tabs = []

  setContext<TabContext>('tabs', { activeTab$, addTab })

  function addTab(label: string, href?: string): number {
      const index = tabs.length;
      tabs = [...tabs, { label, href }];
      return index;
  }
  $: _switchTab(active);
  function _switchTab (tabIndex: number) {
    if (tabIndex < 0 || (tabs.length > 0 && tabIndex >= tabs.length)) {
      console.warn("tabIndex invalid")
      return;
    }
    activeTab$.set(tabIndex);
  }
  export const switchTab = (tabIndex: number) => {
    if (prerender) {

    } else {
      _switchTab (tabIndex)
    }
  }
</script>
<div class="tab-container">
  <ul class="tab-head-container">
  {#each tabs as {label, href}, index}
    <li class="tab-item" class:active={$activeTab$ === index}>
      {#if prerender}
        <a {href} >{label}</a>
      {:else}
      <button  on:click={() => switchTab(index)} >{label}</button>  
      {/if}
    </li>
  {/each}
    <li class="tab-item flex-auto">&nbsp;</li>
  </ul>
  <slot />
</div>
<style lang="postcss">
  :root {
    --tab-height: 100%;
  }
  .tab-container {
    @apply flex justify-between items-center flex-col w-full h-full;
  }
  .tab-head-container {
    @apply flex justify-start items-center w-full grow-0;
  }
  .tab-item {
    @apply px-5 py-1 border-b-2 border-gray-700;
  }
  .active {
    color: #66b851;
    border-color: #66b851;
  }
</style>